package action.user;

import java.io.*;
import java.io.File;
import java.util.*;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import db.*;

@SuppressWarnings("serial")
public class FileAction extends ActionSupport{
	private String file_scId;
	private String file_trId;
	private String file_BId;
	private String coordinate;
	private String file_description;
	private String file_label;
	private java.io.File uploadFile;
	private String uploadFileContentType;
    private String uploadFileFileName;
	
	private static final int BUFFER_SIZE = 16 * 1024 ;
	
	public String getFile_scId() {
		return file_scId;
	}

	public void setFile_scId(String fileScId) {
		file_scId = fileScId;
	}

	public String getFile_trId() {
		return file_trId;
	}

	public void setFile_trId(String fileTrId) {
		file_trId = fileTrId;
	}

	public String getFile_BId() {
		return file_BId;
	}

	public void setFile_BId(String fileBId) {
		file_BId = fileBId;
	}

	public String getCoordinate() {
		return coordinate;
	}

	public void setCoordinate(String coordinate) {
		this.coordinate = coordinate;
	}

	public String getFile_description() {
		return file_description;
	}

	public void setFile_description(String fileDescription) {
		file_description = fileDescription;
	}

	public String getFile_label() {
		return file_label;
	}

	public void setFile_label(String fileLabel) {
		file_label = fileLabel;
	}

	public java.io.File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(java.io.File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public static int getBufferSize() {
		return BUFFER_SIZE;
	}

	@SuppressWarnings("unchecked")
	public String add(){
		Map session = ActionContext.getContext().getSession();
		Integer scId=0;
		Integer trId=0;
		Integer bdId=0;
		try{
			scId = Integer.parseInt(this.getFile_scId());
			trId = Integer.parseInt(this.getFile_trId());
			bdId = Integer.parseInt(this.getFile_BId());
		}catch(Exception e){
			e.printStackTrace();
		}
		if (scId == 0){
			System.out.println("information lost!");
			return ERROR;
		}
		ServiceContractDAO scDao = new ServiceContractDAO();
		ServiceContract temp_sc = scDao.findById(scId);		
		Integer file_uid = temp_sc.getUId();
		String userId = (String)session.get("userId");
		Integer uId = Integer.parseInt(userId);
		if (!file_uid.equals(uId)){
			System.out.println("Wrong privilege!");
			return ERROR;
		}
		
		//Upload File
		String FLocation = this.getFile_label()+ new Date().getTime()+getExtention(this.uploadFileFileName);
		
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload")+"\\";
        java.io.File pdfFile = new File( savePath + FLocation );
        this.copy( uploadFile, pdfFile );
        
		System.out.println("RealPath: "+ServletActionContext.getServletContext().getRealPath("/"));
        
		FileDAO fileDao = new FileDAO();
		org.hibernate.Transaction trans = fileDao.getSession().beginTransaction();
		db.File fileToAdd = new db.File();
		fileToAdd.setServiceContract(temp_sc);
		fileToAdd.setTrId(trId);
		fileToAdd.setBId(bdId);
		fileToAdd.setFLocation(FLocation);
		fileToAdd.setFLabel(this.getFile_label());
		fileToAdd.setFDescription(this.getFile_description());
		fileDao.save(fileToAdd);
		trans.commit();
		//System.out.println("lala"+temp_sc.getScId());
		this.setCoordinate("scId="+file_scId+"&trId="+file_trId+"&BId="+file_BId);
		org.hibernate.Transaction trans2 = scDao.getSession().beginTransaction();
		Set fileSet = temp_sc.getFiles();
		fileSet.add(fileToAdd);
		temp_sc.setFiles(fileSet);
		scDao.save(temp_sc);
		trans2.commit();

		return SUCCESS;
	}
	
	private String getExtention(String fileName)  {
        int pos = fileName.lastIndexOf( "." );
        return fileName.substring(pos);
	}
	
	private void copy(File src, File dst)  {
        try  {
           InputStream in = null ;
           OutputStream out = null ;
            try  {                
               in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
               out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
                byte [] buffer = new byte [BUFFER_SIZE];
                while (in.read(buffer) > 0 )  {
                   out.write(buffer);
               } 
            } finally  {
                if ( null != in)  {
                   in.close();
               } 
                 if ( null != out)  {
                   out.close();
               } 
           } 
        } catch (Exception e)  {
           e.printStackTrace();
       } 
    }	
}
